package org.vectrics.logging;

import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
import org.apache.log4j.spi.LoggingEvent;
//import org.springframework.beans.factory.BeanFactory;
import org.vectrics.common.util.StringUtils;
import org.vectrics.config.ApplicationConfiguration;
import org.vectrics.hibernate.ApplicationContext;
import org.vectrics.system.SystemService;
import org.vectrics.user.PersonService;


public class NotifyAppenderHandlerImpl implements NotifyAppenderHandler {
	private String id = null;
	private NotifyAppenderHandlerThread runningThread = null;
	private SystemService systemService = null;
	private PersonService personProvider = null;
	private ApplicationConfiguration applicationConfiguration = null;
	private ApplicationContext applicationInformation = null;
	private Logger log = Logger.getLogger(this.getClass());
	
	public NotifyAppenderHandlerImpl(String id, ApplicationContext applicationInformation, SystemService systemService, 
			PersonService personProvider,
			ApplicationConfiguration applicationConfiguration) {
		super();
		this.applicationInformation = applicationInformation;
		this.systemService = systemService;
		this.personProvider = personProvider;
		this.applicationConfiguration = applicationConfiguration;
	}
	
	public String getId() {
		return(this.id);
	}
	
	public void handleEvent(LoggingEvent loggingEvent) {
		if (runningThread != null)
			runningThread.blockFromFinishing();
		
		if ((loggingEvent.getLevel().isGreaterOrEqual(Priority.ERROR)) 
				|| ((runningThread != null) && (runningThread.isFinishing() == false))) {
			boolean ignoreMessage = false;
			try {
				String messageText = (String)loggingEvent.getMessage();
				
				if (ignoreMessage == false) {
					if ((runningThread == null) || (runningThread.isFinishing())) {
						this.runningThread = new NotifyAppenderHandlerThread(this.applicationInformation, this.systemService, this.personProvider, this.applicationConfiguration);
						this.runningThread.start();
					}
					this.runningThread.addEvent(loggingEvent);
				}
			} catch (Exception ex) {
				log.info("Exception handling error message: " + ex.getMessage());
			}
		}
		
		if (runningThread != null) {
			try {
				runningThread.releaseBlockFromFinishing();
			} catch (Exception ex) {
				// Ignore exception - could be because running thread finishes 
			}
		}
	}

	public void close() {
	}

	public boolean requiresLayout() {
		return false;
	}

}
